package com.gxa.common;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "接口统一返回对象")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class R<T> {
    @ApiModelProperty(
            name = "code",
            notes = "状态码",
            dataType = "Integer")
    private Integer code;
    @ApiModelProperty(
            name = "msg",
            notes = "系统返回给用户的信息",
            dataType = "String")
    private String msg;
    @ApiModelProperty(
            name = "data",
            notes = "系统返回所携带的所有数据",
            dataType = "T 泛型 所返回的类型根据数据的不同而不同")
    private T data;


    public R fromStatus(Status status) {
        this.setCode(status.getCode());
        this.setMsg(status.getMsg());
        return new R(status.getCode(), status.getMsg(), null);
    }

    public R<T> fromStatus(Status status, T data) {
        this.setCode(status.getCode());
        this.setMsg(status.getMsg());
        this.setData(data);
        return new R(status.getCode(), status.getMsg(), data);
    }

    public static R ok() {
        return new R(Status.SUCCESS.getCode(), Status.SUCCESS.getMsg(), null);
    }

    public static R ok(String msg) {
        return new R(Status.SUCCESS.getCode(), msg, null);
    }

    public static R failure() {
        return new R(Status.SYSTEM_ERROR.getCode(), Status.SYSTEM_ERROR.getMsg(), null);
    }

    public static R failure(String msg) {
        return new R(Status.SYSTEM_ERROR.getCode(), msg, null);
    }

    public static R failure(Status status) {
        return new R(status.getCode(), status.getMsg(), null);
    }
}
